package com.xxxx.yebserver.controller;

import com.xxxx.yebserver.common.R;
import com.xxxx.yebserver.common.utils.JwtTokenUtils;
import com.xxxx.yebserver.entity.Admin;
import com.xxxx.yebserver.pojo.MySecurityUser;
import com.xxxx.yebserver.service.AdminService;
import com.xxxx.yebserver.vo.ChatMessageVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class ChatController {
    public static final String IMAGE_PREFIX = "E:\\java\\yeb\\yeb-server\\src\\main\\resources\\static\\images\\";

    @Autowired
    AdminService adminService;

    @Lazy
    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    @ApiOperation("获取admin的列表")
    @GetMapping("/chat/admin")
    public List<Admin> getAdmins(Authentication authentication,@RequestParam(name = "传入用户名",required = false) String keywords){
        MySecurityUser user = (MySecurityUser) authentication.getPrincipal();
        Admin admin = user.getAdmin();

        if(StringUtils.isEmpty(keywords)){
            List<Admin> list = adminService.getAllAdmin();
            return list.stream()
                    .filter(item->!(item.getAdminId().equals(admin.getAdminId())))
                    .map(item->{
                        item.setPassword(null);
                        return item;
                    })
                    .collect(Collectors.toList());
        }else{
            Admin adminRes = adminService.getAdminByUsername(keywords);
            if(adminRes.getAdminId().equals(admin.getAdminId())) return null;
            adminRes.setPassword(null);
            return Arrays.asList(adminRes);
        }

    }

    @MessageMapping("/ws/chat")
    public void handleMessage(Authentication authentication,ChatMessageVo vo){
        MySecurityUser user = (MySecurityUser) authentication.getPrincipal();
        Admin admin = user.getAdmin();
        vo.setFrom(admin.getUsername());
        vo.setFromNickName(admin.getName());
        vo.setDate(new Date());
        simpMessagingTemplate.convertAndSendToUser(vo.getTo(),"/queue/chat",vo);
    }

    /**
     * 接收转发图片
     * @param req
     * @param imageFile
     * @return
     */
    @PostMapping("/ws/upload/image")
    @ResponseBody
    public R handleUploadImage(HttpServletRequest req,@RequestParam("img")  MultipartFile imageFile,ChatMessageVo vo){
        if(ObjectUtils.isNotEmpty(imageFile)){
            //获取文件名
            String fileName = imageFile.getOriginalFilename();
            String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
            //设置新文件名
            String newFileName = UUID.randomUUID().toString()+fileSuffix;
            String path = IMAGE_PREFIX+newFileName;
            File localImageFile = new File(path);

            try {
                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                MySecurityUser principal = (MySecurityUser)authentication.getPrincipal();
                Admin admin = principal.getAdmin();
                //文件转存到服务器文件中
                imageFile.transferTo(localImageFile);
                vo.setFrom(admin.getUsername());
                vo.setFromNickName(admin.getName());
                vo.setDate(new Date());
                vo.setType(2);
                vo.setContent("/images/"+newFileName);
                simpMessagingTemplate.convertAndSendToUser(vo.getTo(),"/queue/chat",vo);
                return R.ok().data(vo);
            } catch (IOException e) {
               log.error("文件上传失败:{}",e.getMessage());
               return R.error();
            }
        }
        return R.error();
    }
}
